package com.bionic.banking.servlet.filter;

import com.bionic.banking.auth.manager.Config;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class UserAuthFilter implements Filter {

    private ArrayList urlList;

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        //Check if Controller command "login"
        String commandName = (String) req.getParameter("command");
        Boolean isLoginCommandCame = (commandName != null && commandName.equals("login"));
        if (!isLoginCommandCame) {
            String url = request.getServletPath();
            boolean allowedRequest = false;
            // To check if the url can be excluded or not
            for (int i = 0; i < urlList.size(); i++) {
                String strURL = urlList.get(i).toString();
                if (url.startsWith(strURL)) {
                    allowedRequest = true;
                }
            }
            if (!allowedRequest) {
                HttpSession session = request.getSession(false);
                String session_username = session != null
                        ? (String) session.getAttribute(Config.USER_SESSION_KEY)
                        : null;
                // Forward the control to login if session expired or never created
                if (session == null || session_username == null) {
                    String page = Config.getInstance().getProperty(Config.LOGIN);
                    request.getRequestDispatcher(page).forward(request, response);
                }
            }
        }
        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        // Read the URLs to be avoided for authentication check (From web.xml)
        String urls = config.getInitParameter("avoid-urls");
        StringTokenizer token = new StringTokenizer(urls, ",");
        urlList = new ArrayList();
        while (token.hasMoreTokens()) {
            urlList.add(token.nextToken());
        }
    }
}
